package com.xdf.zipperdye.service;

import com.xdf.zipperdye.enums.State;
import com.xdf.zipperdye.model.BillOrder;
import com.xdf.zipperdye.model.OrderDetail;
import com.xdf.zipperdye.model.OrderMain;
import com.xdf.zipperdye.model.Plan;
import com.xdf.zipperdye.utils.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class BillOrderChecker {
    @Autowired
    private PlanService planService;
    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 删除订单明细前调用本方法，检测是否可以删除
     * 存在有效的对应的计划单则不可删除
     * @param iid order_detail.iid
     * @return true表示可以删除，false表示不可删除
     */
    public Boolean check4DelDetail(Integer iid){
        List<Plan> planDetails = planService.getPlan8PidState(iid, State.PLAN_VALID.val());
        return planDetails.size() > 0 ? false : true;
    }

    /**
     * 检测不存在有效明细则可以删除
     * 1. 有关联计划单（有效）则返回 false 不可删除
     * 2. 有关联订单明细（有效）则返回 false 不可删除
     * @param iid order_main.iid
     * @return true表示可以删除，false表示不可删除
     */
    public Boolean check4DelMain(Integer iid){
        List<Plan> plans = planService.getPlan8OrderIdState(iid,State.PLAN_VALID.val());
        if(plans.size()>0) return false;
        List<OrderDetail> details = orderDetailService.getOrderDetail8PidState(iid,State.ORDER_DETAIL_VALID.val());
        if(details.size()>0) return false;
        return true;
    }

    // 修改前调用本方法，检测是否可以修改
    public static Boolean check4Update(BillOrder record){
        if(record == null) throw new BusinessException("空对象无法修改！");
        OrderMain main = record.getMain();
        if(main == null) throw new BusinessException("主表为空无法修改！");
        Integer iid = main.getIid();
        if(iid <= 0) throw new BusinessException("主键为空无法修改！");

        List<OrderDetail> details = record.getDetails();
        if(details.size()<=0) throw new BusinessException("明细为空无法修改！");

        List<OrderDetail> detailsValid = details.stream().filter( item -> Optional.ofNullable(item.getIid()).orElse(0)>0).collect(Collectors.toList());
        if(detailsValid.size()<=0) throw new BusinessException("没有有效明细数据无法修改！");

        return true;
    }

    public static Boolean check4Save(BillOrder record) {
        Boolean ret = false;
        if(record==null) throw new BusinessException("空对象不可保存！");
        OrderMain main = record.getMain();
        if(main==null) throw new BusinessException("主表为空不可保存！");

        List<OrderDetail> details = record.getDetails();
        if(details==null||details.size()<=0) throw new BusinessException("没有明细数据不可保存！");

        ret = true;
        return ret;
    }
}
